import axios from "axios";
import { errorCodeConfig } from "./constant";
import Cookie from "./cache";
import {Toast} from 'vant';
/**
 * 获取系统语言
 * @returns {*|string|string}
 */
function getSysLang() {
  let sysLang = Cookie.get("language") || navigator.language.toLowerCase();
  if (["zh-cn", "en-us"].indexOf(sysLang) === -1) {
    sysLang = "en-us";
  }
  return sysLang || "zh-cn";
}

export const headers = () => {
  const header = {
    'Authorization': Cookie.get("authorization")
  };
  return header;
};

const http = axios.create({
  timeout: 1000*60*60,
  // paramsSerializer: params => querystring.stringify(params),
  validateStatus: function(status) {
    return status >= 200 && status < 300; 
  }
});

// 响应拦截器
http.interceptors.response.use(
  config => {
    const data = config.data;
    if (data.code !== 20000) {
      Toast(data.message)
    }
    return data;
  },
  err => {
    console.warn(err,"err")
    if (err && err.response) {
      const status = err.response.status;
      let errorMessage = errorCodeConfig[status];
      if (status === 404) {
        errorMessage = `${errorMessage}${err.response.config.url}`;
      }
      Toast(errorMessage)
      err.message = errorMessage;
    }
    return Promise.reject(err);
  }
);

/**
 * @param {string} url 必填
 * @returns {Object} params
 */
export const get = async (url, params={},api="VITE_APP_API") => http({
  method: "get",
  url: import.meta.env[api] + url,
  params,
  headers: headers()
})

/**
 * @param {string} url 必填
 * @returns {Object} params
 */
export const post = async (url, params={},api="VITE_APP_API") => http({
  method: "post",
  url: import.meta.env[api] + url,
  data:params,
  headers: headers()
})

export default {get,post};
